package com.hmall.order.interceptors;

import com.hmall.order.utils.ThreadLocalUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author Vsunks.v
 * @Date 2022/8/12 19:49
 * @Blog blog.sunxiaowei.net/996.mba
 * @Description:
 */
public class AuthorizationHandlerInterceptor implements HandlerInterceptor {

    /**
     *目标handler执行之前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.判断请求头是否为空
        String userId = request.getHeader("authorization");
        if (StringUtils.isNotBlank(userId)){
            ThreadLocalUtils.setUserId(userId);
            return true;
        }
        response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        response.setContentType("application/json;charset=UTF=8");

        response.getWriter().write("{\"message\":\"登陆已过期，请重新登陆\"}");
        return false;
    }

    /**
     * 渲染视图之后
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
